package com.leoman.user.controller;

import com.leoman.address.entity.Address;
import com.leoman.address.service.AddressService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.post.entity.PostBase;
import com.leoman.post.service.PostBaseService;
import com.leoman.user.entity.UserCheck;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserCheckService;
import com.leoman.user.service.UserService;
import com.leoman.user.service.impl.UserServiceImpl;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/14 0014.
 */
@Controller
@RequestMapping(value = "admin/user")
public class UserController extends GenericEntityController<UserInfo, UserInfo, UserServiceImpl> {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private PostBaseService postBaseService;

    @Autowired
    private UserCheckService userCheckService;

    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "user/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String mobile,
                     String nickname,
                     Integer gender,
                     Integer status,
                     Integer type,
                     String startDate,
                     String endDate,
                     Integer sort,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {
            int pageNum = getPageNum(start, length);

            Page<UserInfo> page = userService.page(mobile, nickname, gender, status, type, startDate, endDate, null, sort, pageNum, length);
            List<PostBase> postBaseList;
            for (UserInfo userInfo : page.getContent()) {
                // 查询用户发帖数
                postBaseList = postBaseService.findByUserId(userInfo.getId());
                userInfo.setPosts(postBaseList != null ? postBaseList.size() : 0);
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 封禁
     */
    @RequestMapping(value = "/banned")
    @ResponseBody
    public Integer banned(Long userId, Integer status) {

        UserInfo userInfo = userService.queryByPK(userId);
        userInfo.setStatus(status);
        userService.update(userInfo);

        return 1;
    }

    /**
     * 设置为主创
     */
    @RequestMapping(value = "/setCreator")
    @ResponseBody
    public Integer setCreator(Long userId, Integer status) {


        return userService.setCreator(userId, status);
    }

    /**
     * 送馒头确认
     */
    @RequestMapping(value = "/batchConfirm")
    @ResponseBody
    public Integer batchConfirm(Long userId, Long num) {

        UserInfo userInfo = userService.queryByPK(userId);
        /*userInfo.setCoin(userInfo.getCoin() + num);
        userService.update(userInfo);*/

        userIntegralService.changeCoin(userInfo, "系统打赏" + num + "个馒头", Integer.parseInt(num.toString()));

        return 1;
    }

    /**
     * 新增页面
     *
     * @return path
     */
    @RequestMapping(value = "/add")
    public String add() {
        return "user/add";
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail")
    public String detail(Long userId, Model model) {

        UserInfo userInfo = userService.queryByPK(userId);
        if (StringUtils.isNotEmpty(userInfo.getAvater())) {
            userInfo.setAvater(ImageUtil.clearUploadUrl(userInfo.getAvater()));
        }

        List<Address> addressList = addressService.findByUserId(userInfo.getId());

        model.addAttribute("userInfo", userInfo);
        model.addAttribute("addressList", addressList);

        return "user/detail";
    }

    @RequestMapping(value = "/batchSet", method = RequestMethod.POST)
    @ResponseBody
    public Integer batchSet(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            userService.setCreator(id, 1);
        }
        return 1;
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(String mobile,
                        String nickname,
                        String password,
                        Integer gender,
                        MultipartRequest multipartRequest) throws IOException {

        return userService.saveUser(mobile, nickname, password, gender, multipartRequest);
    }


    /**
     * **********************************************************************************************************************
     * 用户审核
     * **********************************************************************************************************************
     */


    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/check/index")
    public String checkIndex() {
        return "check/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/check/list")
    public void checkList(HttpServletResponse response,
                          String userName,
                          String profession,
                          String mobile,
                          Integer status,
                          String startDate,
                          String endDate,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {
            int pageNum = getPageNum(start, length);

            // 将开始时间和结束时间转换为时间戳
            Long startTime = null;
            Long endTime = null;
            if (StringUtils.isNotBlank(startDate)) {
                startTime = DateUtils.stringToLong(startDate, "yyyy-MM-dd hh:mm:ss");
            }
            if (StringUtils.isNotBlank(endDate)) {
                endTime = DateUtils.stringToLong(endDate, "yyyy-MM-dd hh:mm:ss");
            }

            Page<UserCheck> page = userCheckService.page(userName, profession, mobile, status, startTime, endTime, pageNum, length);
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 审核信息详情
     *
     * @return path
     */
    @RequestMapping(value = "/check/info")
    public String checkInfo(ModelMap model, Long id) {
        model.addAttribute("userCheck", userCheckService.getById(id));
        return "check/detail";
    }

    /**
     * 审核通过 or 审核失败
     * 审核通过后将增加主创关联信息
     */
    @RequestMapping(value = "/changeCheckStatus")
    @ResponseBody
    public Integer changeCheckStatus(Long id, Integer status) {
        return userCheckService.changeCheckStatus(id, status);
    }

}
